//
//  ExchangeViewController.m
//  RuntimeDemo
//
//  Created by zxs on 2021/2/24.
//

#import "ExchangeViewController.h"
#import "Person.h"
#import <objc/runtime.h>


@interface ExchangeViewController ()

// 交换按钮，记忆按钮的状态
@property (weak, nonatomic) IBOutlet UISwitch *exchangeSwitch;

@property (strong, nonatomic) Person *person;

// 记忆是否交换过
@property (assign, nonatomic) BOOL isChanged;

@end

@implementation ExchangeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.person = [[Person alloc] init];
}

#pragma mark - action
// 根据记忆状态，交换函数执行体
- (IBAction)exchangeSwitchChanged:(id)sender {
    // 还没有交换过，并且要求交换；那么交换一次
    if ((self.exchangeSwitch.isOn) && !self.isChanged) {
        [self change];
        self.isChanged = YES;
    }
    
    // 已经交换过，并且要求没交换前的原始函数；那么交换一次，交换回来
    if ((!self.exchangeSwitch.isOn) && self.isChanged) {
        [self change];
        self.isChanged = NO;
    }
}

// 写代码
- (IBAction)writeButtonTouched:(id)sender {
    NSLog(@"写代码按钮被点击");
    [self.person coding];
}

// 吃饭
- (IBAction)eatButtonTouched:(id)sender {
    NSLog(@"吃饭按钮被点击");
    [self.person eating];
}

#pragma mark - private
// 执行交换
- (void)change {
    Method codingMethod = class_getInstanceMethod(self.person.class, @selector(coding));
    Method eatingMethod = class_getInstanceMethod(self.person.class, @selector(eating));
    method_exchangeImplementations(codingMethod, eatingMethod);
}


@end
